package com.ruoyi.web.controller.app;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.ResponseResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusiException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.OrderService;
import com.ruoyi.system.vo.OrderCountVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "用户端:订单相关接口-----代收订单")
@RestController
@RequestMapping("/app/order")
public class OrderController extends AppController {
    @Resource
    private OrderService orderService;
    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private ISysConfigService iSysConfigService;

    @ApiOperation(value = "每隔5秒获取订单数量")
    @GetMapping("getOrderNum")
    public ResponseResult<OrderCountVo> getOrderNum() {
        Long userId = this.getUserId();
        SysUser sysUser = iSysUserService.getById(userId);
        Order order = new Order();
        order.setUserId(userId);
        order.setRemindStatus(0);
        int count = orderService.countByDomain(order);

        orderService.updateDomainNullId(order, "remind_status", 1);
        Map<String, Object> map = new HashMap<>();
        map.put("num", count);
        map.put("orderStatus", sysUser.getOrderStatus());
        //剩余时间
        Date orderStatusTime = sysUser.getOrderStatusTime();

        map.put("expireTime", Constants.closeTime*60);
        map.put("closeMin", Constants.closeTime);
        return this.setSuccessResult(map);
    }


    @ApiOperation(value = "获取统计数据")
    @PostMapping("getCount")
    public ResponseResult<OrderCountVo> getCount() {
        Long userId = this.getUserId();
        OrderCountVo count = orderService.count(userId);
        return this.setSuccessResult(count);
    }


    @ApiOperation(value = "订单详情")
    @PostMapping("getById")
    public ResponseResult getById(Long id) {
        Long userId = this.getUserId();
        Order order = orderService.checkOrder(userId, id);
        return this.setSuccessResult(order);
    }


    @ApiOperation(value = "订单查询")
    @GetMapping("list")
    public ResponseResult<List<Order>> list(String status, String orderNo, PageDomain pageDomain) {
        //startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Order order = new Order();
        order.setUserId(loginUser.getUserId());
        if (StrUtil.isNotBlank(status)) {
            order.setStatus(status);
        }
        if (StrUtil.isNotBlank(orderNo)) {
            order.setOrderNo(orderNo);
        }

        DateTime begin = DateUtil.beginOfDay(new Date());
        begin = DateUtil.offsetDay(begin, -1);
        pageDomain.setBeginTime(DateUtil.formatTime(begin));
        pageDomain.setEndTime(DateUtil.now());
        List<Order> list = orderService.findList(order, pageDomain);
        List<Order> collect = list.stream().map(p -> p.setAmount(p.getPayAmount())).collect(Collectors.toList());
        return this.setSuccessResult(collect);
    }

    @Log(title = "订单确认收款", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @ApiOperation(value = "订单确认收款")
    @PostMapping("finish")
    public ResponseResult finish(Long id, BigDecimal confirmAmount) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Order order = orderService.check(id);
        if (!NumberUtil.equals(order.getPayAmount(), confirmAmount)) {
            throw new BusiException("金额错误");
        }
        orderService.finish(loginUser.getUserId(), id);
        return this.setSuccessResult();
    }

    @Log(title = "超时补单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "超时补单")
    @RepeatSubmit
    @PostMapping("reduce")
    public ResponseResult reduce(Long id, BigDecimal confirmAmount) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Order order = orderService.check(id);
        if (!NumberUtil.equals(order.getPayAmount(), confirmAmount)) {
            throw new BusiException("金额错误");
        }
        orderService.reduce(loginUser.getUserId(), id);
        return this.setSuccessResult();
    }

    @Log(title = "未收到款-上传图", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "未收到款")
    @RepeatSubmit
    @PostMapping("submitPic")
    public ResponseResult submitPic(@Valid @RequestBody Order order) {
        if (StrUtil.isBlank(order.getTradePic())) {
            throw new BusiException("请检查截图是否正确,图片不能大于2M");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Order domain = orderService.check(order.getId());
        if (domain.getFreezeStatus() != 1) {
            throw new BusiException("订单已处理完,请刷新后查看");
        }

        String s = iSysConfigService.selectConfigByKey("submitPic");
        Integer minute = 3;

        try {
            minute = Integer.valueOf(s);

        } catch (Exception e) {

        }
        Date createTime = domain.getCreateTime();
        createTime = DateUtil.offsetMinute(createTime, minute);
        if (createTime.getTime() > new Date().getTime()) {
            throw new BusiException("请" + minute + "分钟后再上传图，以此确认是否到账");
        }
        domain = new Order();
        domain.setId(order.getId());
        domain.setTradePic(order.getTradePic());
        domain.setTradeTime(new Date());
        orderService.updateDomain(domain);
        return this.setSuccessResult();
    }


}
